import 'package:account_book/common/entity/category.dart';
import 'package:account_book/common/utils/toast_util.dart';
import 'package:account_book/routes/app_routes.dart';
import 'package:bruno/bruno.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import './index.dart';

class EnrollPage extends GetView<EnrollController> {
  const EnrollPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(context),
      body: _buildBody(context),
      backgroundColor: Colors.white,
    );
  }

  BrnAppBar _buildAppBar(BuildContext context) {
    return BrnAppBar(
      title: "记一笔",
    );
  }

  Widget _buildBody(BuildContext context) {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(3),
      child: Form(
        key: controller.formKey,
        child: Column(
          children: [
            FormField<String>(
              initialValue: controller.state.amount,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return "请输入金额";
                }
                return null;
              },
              onSaved: (value) {
                controller.state.amount = value;
              },
              builder: (FormFieldState<String> formFieldState) {
                return BrnTextInputFormItem(
                  title: "金额",
                  unit: "元",
                  hint: "请输入金额",
                  isRequire: true,
                  autofocus: true,
                  inputType: BrnInputType.decimal,
                  error: formFieldState.errorText ?? "",
                  inputFormatters: [
                    FilteringTextInputFormatter(RegExp("[0-9.]"), allow: true),
                  ],
                  onChanged: (value) {
                    formFieldState.didChange(value);
                  },
                );
              }
            ),
            FormField<String>(
              initialValue: controller.state.createDate,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return "请选择日期";
                }
                return null;
              },
              onSaved: (value) {
                controller.state.createDate = value;
              },
              builder: (FormFieldState<String> formFieldState) {
                return BrnTextSelectFormItem(
                  title: "日期",
                  value: formFieldState.value,
                  error: formFieldState.errorText ?? "",
                  isRequire: true,
                  onTap: () {
                    BrnDatePicker.showDatePicker(
                      context,
                      initialDateTime: DateTime.now(),
                      pickerTitleConfig: BrnPickerTitleConfig.Default,
                      dateFormat: 'yyyy年,MMMM月,dd日',
                      pickerMode: BrnDateTimePickerMode.date,
                      onConfirm: (dateTime, list) {
                        formFieldState.didChange(DateUtil.formatDate(dateTime, format: "yyyy-MM-dd"));
                      }
                    );
                  }
                );
              }
            ),
            FormField<String>(
                initialValue: controller.state.remark,
                onSaved: (value) {
                  controller.state.remark = value;
                },
                builder: (FormFieldState<String> formFieldState) {
                  return BrnTextBlockInputFormItem(
                    title: "备注",
                    hint: "请输入",
                    minLines: 1,
                    maxLines: 5,
                    onChanged: (newValue) {
                      formFieldState.didChange(newValue);
                    },
                  );
                }
            ),
            DefaultTabController(
              length: 2,
              child: BrnTabBar(
                tabs: [BadgeTab(text: "支出"),BadgeTab(text: "收入")],
                onTap: (state, index) {
                  controller.switchType(index + 1);
                },
              ),
            ),
            Container(
              padding: const EdgeInsets.only(top: 10,bottom: 10),
              height: 200,
              child: SingleChildScrollView(
                child: Obx(() {
                  final categoryList = controller.state.categoryData;
                  if (categoryList.isEmpty) {
                    return BrnAbnormalStateWidget(
                      isCenterVertical: true,
                      title: "暂无数据！",
                      content: "请先添加类别",
                    );
                  } else {
                    final list = <String>[];
                    for(Category category in categoryList) {
                      list.add(category.name);
                    }
                    return BrnSelectTag(
                        tags: list,
                        spacing: 12,
                        alignment: Alignment.center,
                        onSelect: (selectedIndexes) {
                          final category = controller.state.categoryData[selectedIndexes[0]];
                          controller.state.categoryId = category.id;
                          controller.state.categoryName = category.name;
                        });
                  }

                }),
              ),
            ),
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 50),
              padding: const EdgeInsets.only(bottom: 20),
              child: BrnBigMainButton(
                title: "记一笔",
                onTap: () async {
                  final currentState = controller.formKey.currentState;
                  if (currentState!=null && currentState.validate()) {
                    currentState.save();
                    if (controller.state.categoryId == null) {
                      ToastUtil.show("请选择类别");
                      return;
                    }
                    await controller.saveExpense();
                  }
                },
              ),
            )
          ],
        ),
      )
    );
  }

}